package com.demo.redis.config;

import com.demo.redis.utils.PrefixRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import java.nio.charset.StandardCharsets;

/**
 * @author peter
 * @date 2022/2/15 11:09
 */
@Configuration
@SuppressWarnings({"unchecked", "rawtypes"})
public class PrefixRedisConfiguration {

    @Value("${spring.redis.prefix:}")
    private String prefix;

    @Bean(name = "redisTemplate2")
    @ConditionalOnMissingBean(name = "redisTemplate2")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // PrefixRedisSerializer 自定义序列化，增加了前缀
        redisTemplate.setKeySerializer(new PrefixRedisSerializer(StandardCharsets.UTF_8, this.prefix));
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new PrefixRedisSerializer(StandardCharsets.UTF_8, this.prefix));
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        return redisTemplate;
    }

}
